package com.bugreport.configuration;

import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.bugreport.trackers.BugTrackerConnector;
import com.bugreport.utils.BugReportException;

public abstract class BugTrackerConfiguration implements ApplicationContextAware {

	public static final String BUG_TRACKER_KEY = ".type";
	public static final String URL_PATTERN_MATCHER = ".urlpatternmatcher";
	public static final String SPRING_BEAN_SUFFIX = "Configuration";

	private Integer idConfig;
	private String bugTrackerKey;
	private String urlPatternMatcher;

	private ApplicationContext context;

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

	public Integer getIdConfig() {
		return idConfig;
	}

	protected void setId(Integer idConfig) {
		this.idConfig = idConfig;
	}

	public String getBugTrackerKey() {
		return bugTrackerKey;
	}

	protected void setBugTrackerKey(String bugTrackerKey) {
		this.bugTrackerKey = bugTrackerKey;
	}

	public String getUrlPatternMatcher() {
		return urlPatternMatcher;
	}

	protected void setUrlPatternMatcher(String urlPatternMatcher) {
		this.urlPatternMatcher = urlPatternMatcher;
	}

	public boolean isUrlMatching(String url) {
		Pattern pattern = Pattern.compile(urlPatternMatcher);
		Matcher matcher = pattern.matcher(url);
		return matcher.matches();
	}

	public BugTrackerConnector getConnector() {
		return (BugTrackerConnector) context.getBean(getConnectorSpringId(), new Object[] { this });
	}

	protected abstract String getConnectorSpringId();

	protected static String getProperty(Properties properties, String key, boolean mandatory) throws BugReportException {

		String value = (String) properties.get(key);

		if (mandatory && value == null) {
			throw new BugReportException(200, key);
		}

		return value;
	}

	protected static String getBugTrackerKey(Properties properties, Integer configId) throws BugReportException {
		return getProperty(properties, composeKey(configId.toString(), BUG_TRACKER_KEY), true);
	}

	protected static String getUrlPatternMatcher(Properties properties, Integer configId) throws BugReportException {
		return getProperty(properties, composeKey(configId.toString(), URL_PATTERN_MATCHER), true);
	}

	private static String composeKey(String... parts) {
		String key = "";
		for (String part : parts) {
			key = key.concat(part);
		}
		return key;
	}

	protected static String composeKey(Integer idConfig, String... parts) {
		return idConfig.toString().concat(composeKey(parts));
	}
}
